import WS from 'nodejs-websocket';
import { Player } from './Player';
import { Room } from './Room';

export const VERSION:string = "2022.8.13";           //版本号

let id_num = 1;     //登录用户给一个id值，1-10000 递增就好
let roomId_num = 1; //房间给一个id值，1-10000 递增就好
const all_players:Set<Player> = new Set();     //全部玩家
export const arr_hallPlayer:Set<Player> = new Set();     //在大厅的全部玩家
export const map_room:Map<number,Room> = new Map();             //所有房间
                
export const createServer = () => {

  console.log("野棋后台服务器启动完成")

  WS.createServer(connection => {

    //连接客户端
    const player = onOpen(connection)
    
    //收到消息监听
    connection.on('text', function(result:string) {
      onMessage(player,result)
    })

    //掉线监听
    connection.on('close', function(code:number) {      //nodejs低高版本都会执行这个
      console.log("掉线：close");
      onClose(connection)
    })

    //掉线监听
    connection.on('error', function(code:number) {      //nodejs高版本会执行这个
      console.log("掉线：error");
      onClose(connection)
    })

  }).listen(8082)
}

/**
 * 客户端连接
 */
function onOpen(connection:any){
  const player = new Player(id_num<10000?id_num++:1,connection)
  all_players.add(player)
  arr_hallPlayer.add(player)
  const obj = {other:"playerId",id:player.id}
  sendObj(connection,obj)
  numOfHallPlayers()
  return player
}

/**
 * 收到消息监听
 */
function onMessage(player:Player,msg:string){
  const obj = JSON.parse(msg);
  if(obj.other!=null){          
    //大厅操作
    switch(obj.other){
      case "index":
        if(!arr_hallPlayer.has(player)){
          arr_hallPlayer.add(player);
          numOfHallPlayers();
        }
        break;
      case "check_version":
        player.checkVersion(obj.version);
        break;
      case "matching_cancel":
        player.cancel();
        break;
      case "matching" :
        player.matching(obj);
        break;
      default: console.error("未知other: ",obj.other);
    }
  }else{
    //大厅
    const room = map_room.get(player.roomId)
    room&&room.onMessage(obj)
  }
}

/**
 * 客户端掉线
 */
function onClose(connection:any){
  all_players.forEach(plyer=>{
    if(plyer.connection == null || plyer.connection == connection ){
      all_players.delete(plyer)
      arr_hallPlayer.delete(plyer)
      plyer.dropLine();
      console.log("玩家掉线："+plyer.id)
      numOfHallPlayers()
    }
  })
}

/**
 * 通知大厅玩家在线人数
 */
export function numOfHallPlayers(){
  const obj = {other:"numOfHallPlayers",numOfHallPlayers:arr_hallPlayer.size}
  arr_hallPlayer.forEach(player=>{
    sendObj(player.connection,obj)
  })
  console.log("当前大厅在线人数："+obj.numOfHallPlayers)
}


/**
 * 发送obj
 */
export function sendObj(connection:any,obj:any){
  if(connection!=null){
    connection.sendText(JSON.stringify(obj))
  }
}

/**
 * 创建Room
 */
export function createRoom(type:number){
  return new Room(roomId_num<10000?roomId_num++:1,type);
}